package com.newsnetwork.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.newsnetwork.api.service.BaseService;
import com.newsnetwork.enums.UserStatus;
import com.newsnetwork.pojo.AppUser;
import com.newsnetwork.user.mapper.AppUserMapper;
import com.newsnetwork.user.service.AppUserMngService;
import com.newsnetwork.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author: HuangDekai
 * @date: 2022/11/10 21:20
 * @version: 1.0
 * @since: jdk8
 * @description: 与 admin 管理用户相关的 Service 的 实现, 可以分页查询用户列表
 */
@Service
public class AppUserMngServiceImpl extends BaseService implements AppUserMngService {

    @Autowired
    private AppUserMapper appUserMapper;

    /**
     * 查询用户列表
     * @param nickname 用户昵称
     * @param status 用户状态
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param page 分页中的第几页
     * @param pageSize 每页有几条记录
     * @return 分页的用户列表结果
     */
    @Override
    public PagedGridResult queryAllUserList(String nickname,
                                            Integer status,
                                            Date startDate,
                                            Date endDate,
                                            Integer page,
                                            Integer pageSize) {
        Example example = new Example(AppUser.class);
        // 设置按时间倒序排序
        example.orderBy("createdTime").desc();
        Example.Criteria criteria = example.createCriteria();

        // 当用户名不为空时, 模糊查询
        if (StringUtils.isNotBlank(nickname)) {
            criteria.andLike("nickname", "%" + nickname);
        }
        if (UserStatus.isUserStatusValid(status)) {
            criteria.andEqualTo("activeStatus", startDate);
        }
        if (startDate != null) {
            criteria.andGreaterThanOrEqualTo("createdTime", startDate);
        }
        if (endDate != null) {
            criteria.andGreaterThanOrEqualTo("endTime", endDate);
        }

        PageHelper.startPage(page, pageSize);
        List<AppUser> list = appUserMapper.selectByExample(example);

        return setterPagedGrid(list, page);
    }

    /**
     * 将指定用户冻结或解冻
     *
     * @param userId   用户id
     * @param doStatus 用户要更改的状态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void freezeUserOrNot(String userId, Integer doStatus) {
        AppUser appUser = new AppUser();
        appUser.setId(userId);
        appUser.setActiveStatus(doStatus);

        appUserMapper.updateByPrimaryKeySelective(appUser);
    }
}
